package org.kfive.nova;

import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.kfive.nova.test.model.Address;
import org.kfive.nova.test.model.User;
import org.kfive.nova.test.service.AddressService;
import org.kfive.nova.test.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/*
* AtomJmeterTest.java
* Created  by  dell
* Created on 2016/3/28 14:30
*/
public class AtomJmeterTest extends AbstractJavaSamplerClient {

    private static UserService userService;

    private static AddressService addressService;


    private Logger LOG = Logger.getLogger(AtomJmeterTest.class);

    static {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        userService = context.getBean(UserService.class);
        addressService = context.getBean(AddressService.class);
    }

    private void testTranscation(){
        LOG.info("创建用户");
        User user = new User();
        Address address = new Address();
        user.setName("叮当");
        user.setAge(29);
        user.setCompany("叮当快药（北京）科技有限公司");
        user.setHeight(170.0d);
        user.setPosition("开发工程师");
        user.setSex(1);
        user.setTitle("开发工程师");
        user.setWeight(60.0d);
        Integer userId = userService.saveUser(user);
        LOG.info("创建地址");
        address.setCounty("中华人民共和国");
        address.setProvince("河北省");
        address.setStreet("XXX");
        address.setTown("范庄镇");
        address.setDetailAddress("中国河北省石家庄市XXXXXXXXX");
        Integer addressId = addressService.saveAddress(address);
        LOG.info("用户ID"+userId+":"+"地址ID"+addressId);
        Assert.assertNotNull("用户保存失败",userId);
        Assert.assertNotNull("地址保存失败",addressId);
    }

    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        SampleResult result = new SampleResult();
        result.sampleStart();
        try {
            testTranscation();
            result.setSuccessful(true);
        }catch (Exception e){
            result.setSuccessful(false);
            e.printStackTrace();
        }finally {
            result.sampleEnd();
        }
        return result;
    }
}
